import org.openjdk.jmh.annotations.*
import org.openjdk.jmh.infra.Blackhole
import java.util.concurrent.TimeUnit
import kotlin.random.Random

/**
 * KUYA UI性能基准测试类
 * 用于比较不同编译器在UI渲染、事件处理等操作上的性能差异
 */
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(value = 2, jvmArgsAppend = ["-Xms2g", "-Xmx2g"])
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
class PerformanceBenchmark {
    // 模拟数据
    private lateinit var testData: List<Int>
    private lateinit var testStrings: List<String>
    
    @Setup
    fun setup() {
        // 初始化测试数据
        testData = List(10000) { Random.nextInt() }
        testStrings = List(10000) { "TestString\${Random.nextLong()}" }
    }
    
    /**
     * 测试基本计算性能
     */
    @Benchmark
    fun testBasicComputation(): Int {
        var sum = 0
        for (i in testData) {
            sum += i * i
        }
        return sum
    }
    
    /**
     * 测试字符串处理性能
     */
    @Benchmark
    fun testStringProcessing(): Int {
        var result = 0
        for (str in testStrings) {
            result += str.hashCode()
            result += str.length
            result += str.substring(0, Math.min(5, str.length)).hashCode()
        }
        return result
    }
    
    /**
     * 测试集合操作性能
     */
    @Benchmark
    fun testCollectionOperations(): List<Int> {
        return testData
            .filter { it % 2 == 0 }
            .map { it * 2 }
            .sorted()
            .take(1000)
    }
    
    /**
     * 测试并发性能
     */
    @Benchmark
    @Threads(4)
    fun testConcurrentProcessing(blackhole: Blackhole) {
        val parallelSum = testData.parallelStream()
            .filter { it > 0 }
            .mapToInt { it }
            .sum()
        blackhole.consume(parallelSum)
    }
    
    /**
     * 测试内存分配性能
     */
    @Benchmark
    @Measurement(iterations = 5)
    fun testMemoryAllocation(blackhole: Blackhole) {
        val list = ArrayList<Int>(1000)
        for (i in 0 until 1000) {
            list.add(i)
        }
        blackhole.consume(list)
    }
}